<template>
  <Header style="margin-bottom: 20px"></Header>
  <div class="showcart-detail">
    <div class="circle" style="float: left">FC</div>
    <p>
      <span
          style="color: rgb(242, 89, 75); font-family: Microsoft YaHei; font-size: 20px; line-height: 140%;">鲜花结算</span>
    </p>
    <p>
        <span
            style="color: rgb(102, 102, 102); font-family: Microsoft YaHei; font-size: 10px; letter-spacing: 0px; line-height: 140%;">
        FLOWER CHECKOUT
        </span><br>
    </p>
    <div class="showcart-table">
      <el-table
          ref="multipleTableRef"
          :data="data.product"
          style="width: 100%;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);color: #737373"
          @selection-change="handleSelectionChange"
      >
        <el-table-column >
          <template #default="scope">
            <img :src="scope.row.imageUrl" alt="产品图片" style="width: 120px; height: 120px;margin:15px 20px 0"/>
          </template>
        </el-table-column>
        <el-table-column property="flowerName" label="名称"/>
        <el-table-column property="price" label="单价"/>
        <el-table-column property="quantity" label="购买数量">
          <template #default="scope">
            <el-input-number
                v-model="scope.row.quantity"
                @change="handleQuantityChange(scope.row, scope.$index)"
                size="small"
                :min="1"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="showcart-form">
      <el-form :model="data.form" :rules="data.rules" ref="formRef">
        <p style="font-size: 17px;margin-bottom: 15px;font-family: 黑体;font-weight: bold">收件人信息</p>
        <el-form-item label="收&nbsp;货&nbsp;人&nbsp;" prop="addressee">
          <el-input v-model="data.form.addressee" placeholder="请填写收货人姓名"
                    style="width: 300px;height: 30px;font-weight: bold;"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="data.form.phoneNumber" placeholder="请填写收货人手机号码"
                    style="width: 300px;height: 30px"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="deliveryAddress">
          <el-input v-model="data.form.deliveryAddress" placeholder="所在地区，街道、小区、楼栋门牌号等"
                    style="width: 300px;height: 30px"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="container">
      <div class="showcart-sett flex-container">
        <a href="/Buy" class="sett-left">
          <el-icon>
            <Pointer/>
          </el-icon>
          继续挑选</a>
        <div class="sett-right">
          应付金额:&nbsp;<span>¥</span><span>{{ totalSelectedPrice }}</span>
        </div>
        <el-button @click="settlement" class="sett-button" type="primary" id="jiesuan">去结算</el-button>
      </div>
    </div>
  </div>
  <Footer></Footer>
</template>

<script setup>
import request from "@/utils/request";
import {computed, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router";
import {useRoute} from "vue-router";

const route = useRoute();
const formRef = ref()

const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-pro-user")),
  product: [],
  num: route.query.num,
  productId: route.query.product,
  form: {
    addressee: '',
    phoneNumber: '',
    deliveryAddress: ''
  },
  allPrice: 0,
  price: [],
  inorder: {},
  rules: {
    addressee: [
      {required: true, message: '请输入收件人', trigger: 'blur'}
    ],
    phoneNumber: [
      {required: true, message: '请输入手机号', trigger: 'blur'},
      {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
    ],
    deliveryAddress: [
      {required: true, message: '请输入收货地址', trigger: 'blur'}
    ]
  }
})


if(route.query.product){
  request.get("/shoppingcart/getAll", {
    params: {
      userId: route.query.product
    }
  }).then(res => {
    data.product = res.data
    for(let i=0;i<data.product.length;i++){
      data.product[i].checked=(res.data[i].checked==="true")
    }
    console.log(data.product)
  })
}else {
  request.get("/shoppingcart/getChecked", {
    params: {
      userId: data.user.id
    }
  }).then(res => {
    data.product = res.data
    for(let i=0;i<data.product.length;i++){
      data.product[i].checked=(res.data[i].checked==="true")
    }
  })
}

const totalSelectedPrice = computed(() => {
  return data.product
      .filter(product => product.checked===true)
      .reduce((sum, product) => sum + parseFloat(product.price.replace('￥', '')) * product.quantity, 0);
});

const handleQuantityChange = (value) => {
  data.num = value
  data.allPrice = 0
  setTimeout(() => {
    for (let i = 0; i < data.product.length; i++) {
      let price = parseFloat(data.product[i].price)
      let product = parseFloat(data.product[i].quantity)
      data.price[i] = price * product
      data.allPrice += data.price[i]
    }
  }, 50)
}


setTimeout(() => {
  for (let i = 0; i < data.product.length; i++) {
    let price = parseFloat(data.product[i].price)
    let product = parseFloat(data.product[i].quantity)
    data.price[i] = price * product
    data.allPrice += data.price[i]
  }
}, 500)

const settlement = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("购买成功")
      for (let i = 0; i < data.product.length; i++) {
        data.inorder.userId = data.user.id
        data.inorder.flowerId = data.product[i].flowerId
        data.inorder.addressee = data.form.addressee
        data.inorder.orderDate = ""
        data.inorder.quantity = data.product[i].quantity
        data.inorder.orderStatus = "未发货"
        data.inorder.totalAmount = data.price[i]
        data.inorder.phoneNumber = data.form.phoneNumber
        data.inorder.deliveryAddress = data.form.deliveryAddress
        console.log(data.inorder)
        request.post("/order", data.inorder).then(res => {
          console.log(data.form)
          if (res.code === '0') {
            setTimeout(() => {
              router.push({path: '/Buy'})
            }, 1000)
          } else {
            ElMessage.error("购买失败")
          }
        })
        request.delete("/shoppingcart/" + data.product[i].itemId).then(res => {
          if (res.code === '0') {
            console.log("删除成功")
          } else {
            console.log("删除失败")
          }
        })
      }
    } else {
      ElMessage.success("请正确输入购买信息")
    }
  })
}


</script>


<style>
.showcart-detail {
  width: 60%;
  margin: 0 auto;
}

.showcart-form {
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #fff;
}

.showcart-sett {
  width: 100%;
  height: 50px;
  margin-top: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.container {
  display: flex;
  width: 100%;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box; /* 确保padding不会增加宽度 */
  color: #bebebe;
}

.sett-left {
  color: #bebebe;
  text-decoration: none;
  margin-left: 20px;
}

.sett-right {
  margin-left: auto; /* 确保右边距自动调整，使其靠右 */
  margin-right: 20px;
}

.sett-right span {
  color: #f2594b;
}

.sett-button {
  width: 15%; /* 占10%的宽度 */
  height: 50px;
  box-sizing: border-box; /* 确保padding不会增加宽度 */
  background-color: #f2594b;
  color: #FFFFFF;
}

.sett-button:hover {
  background-color: #ee2b2b;
  color: #FFFFFF;
}

.circle {
  margin-bottom: 30px;
  margin-top: 10px;
  margin-right: 5px;
  width: 30px;
  height: 30px;
  background-color: #ff6347;
  border-radius: 50%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  line-height: 180%;
  color: #FFFFFF;
  text-align: center;
}
</style>